package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mf.entity.po.Dictionary;
import com.mf.entity.vo.ListKeyValue;
import com.mf.mapper.DictionaryMapper;

import com.mf.service.IDictionaryService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 数据字典 服务实现类
*
* @author mf
* @since 2024-07-05
*/
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {
    @Resource
    private DictionaryMapper dictionaryMapper;

    /**
     * 修改状态
     */
    @Override
    @Transactional
    public Integer changeStatus( Integer id,Integer status) {
        Dictionary dictionary = new Dictionary();
        dictionary.setStatus(status);
        dictionary.setId(id);
        return dictionaryMapper.updateById(dictionary);
    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public Boolean delete(List<Integer> ids) {
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dictionary::getId, ids) ;
        return dictionaryMapper.delete(queryWrapper) > 0;
    }

    /**
     * 新增
     */
    @Override
    @Transactional
    public void add(Dictionary dictionary) {
        List<Dictionary> saveDictionaryList = new ArrayList<>();
        String[] codeArray = dictionary.getCode().split(";");

        for (String code : codeArray) {
            Dictionary dictionary1 = new Dictionary();

            dictionary1.setCode(code);

            dictionary1.setDctValue(dictionary.getDctValue());
            dictionary1.setDvtLabel(dictionary.getDvtLabel());

            dictionary1.setEditRole(dictionary.getEditRole());

            dictionary1.setSystemCode(dictionary.getSystemCode());

            dictionary1.setSort(dictionary.getSort());
            dictionary1.setPid(dictionary.getPid());

            saveDictionaryList.add(dictionary1);
        }
        dictionaryMapper.batchSave(saveDictionaryList);
    }

    /**
     * 根据编号查询
     */
    @Override
    public List<ListKeyValue<Dictionary>>  findByCode(String code) {
        // 将code按照逗号进行分割批量保存
        String[] codeArray = code.split(",");
        List<Dictionary> codeList = dictionaryMapper.findByCode(codeArray);
        // 如果有数据使用map code字段进行分组
        Map<String, List<Dictionary>> collect = codeList.stream().collect(Collectors.groupingBy(Dictionary::getCode));

        if(codeList.isEmpty()){
            return Collections.emptyList();
        }

        return new ListKeyValue<Dictionary>().setList(collect);
    }
}
